#ifndef _COMMON_H
#define _COMMON_H

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <pthread.h>
#include <unistd.h>
#include <dlfcn.h>
#include <inttypes.h>
#include <sys/time.h>

#define VERSION "1.0.0"
#define GW_CFG_SYS ("./cfg/SYS.json")
#define GW_CFG_CLT ("./cfg/CLT.json")
#define GW_CFG_RULE ("./cfg/RULE.json")
#define GW_CFG_AUTOPROBE ("./cfg/AUTOPROBE.json")


typedef struct 
{
    // 调试等级
    int debug_level;
    // 运行时长
    int run_time;
}g_param_t;

#include "core/config.h"
#include "core/msg.h"

typedef struct
{
    cfg_basic_t *g_basic;   // 基本配置
    cfg_temp_t *g_template;
    cfg_pu_t *g_coll_link;  // 采集通道链表
    cfg_pu_t *g_trans_link; // 转发通道链表
} g_cfg_t;

extern g_param_t g_param;
extern g_cfg_t* g_cfg;


typedef int (*finit) (cfg_pu_t* pu);
typedef int (*frun) (cfg_pu_t* pu);

typedef struct 
{
    // 初始化协议、设备模板
    finit init;
    // 通道运行线程
    frun run;
    // 通道消息处理
    fmsg msg;
}dlmodule_t;

extern dlmodule_t ModbusHost_RTU_Addr;
extern dlmodule_t EIOT;
extern dlmodule_t AWTIOT;

typedef struct 
{
    // 消息方法
    fmsg transport_message;
    // 日志打印
    void (*log_p)(char* probe,int level,const char *format, ...);
}api_t;


/*
 * The color for terminal (foreground)
 * BLACK    30
 * RED      31
 * GREEN    32
 * YELLOW   33
 * BLUE     34
 * PURPLE   35
 * CYAN     36
 * WHITE    37
 */
#define _DBG_LOG_HDR(name,lvl,color_n)                    \
    printf("\033["#color_n"m["name"/"lvl"] ")
#define _DBG_LOG_X_END                                     \
    printf("\033[0m\n")

/*
 * static debug routine
 * NOTE: This is a NOT RECOMMENDED API. Please using LOG_X API.
 *       It will be DISCARDED later. Because it will take up more resources.
 */
#define dbg_log_line(name,lvl, color_n, fmt, ...)                \
    do                                                      \
    {                                                       \
        _DBG_LOG_HDR(name,lvl, color_n);                         \
        printf(fmt, ##__VA_ARGS__);                     \
        _DBG_LOG_X_END;                                     \
    }                                                       \
    while (0)

#define LOG_D(name,fmt, ...)      dbg_log_line(name,"D", 0, fmt, ##__VA_ARGS__)
#define LOG_I(name,fmt, ...)      dbg_log_line(name,"I", 32, fmt, ##__VA_ARGS__)
#define LOG_W(name,fmt, ...)      dbg_log_line(name,"W", 33, fmt, ##__VA_ARGS__)
#define LOG_E(name,fmt, ...)      \
    do{ \
        printf("%s %d ",__FILE__,__LINE__); \
        dbg_log_line(name,"E", 31, fmt, ##__VA_ARGS__); \
    }while(0) \


#include "public/cJSON.h"
#include "public/util.h"
#include "public/rtlist.h"
#include "public/platform.h"

#endif